package com.payment.ktb.activity.main4;

import android.app.Dialog;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.payment.ktb.Interface.AlertInterface;
import com.payment.ktb.Interface.HttpCallbackListener;
import com.payment.ktb.R;
import com.payment.ktb.activity.BaseActivity;
import com.payment.ktb.constants.Constants;
import com.payment.ktb.constants.ConstantsPay;
import com.payment.ktb.constants.ConstantsSettle;
import com.payment.ktb.constants.ConstantsUser;
import com.payment.ktb.constants.HttpActions;
import com.payment.ktb.constants.HttpUrls;
import com.payment.ktb.utils.AlertDialogUtils;
import com.payment.ktb.utils.HttpUtils;
import com.payment.ktb.utils.Md5Utils;
import com.payment.ktb.utils.SharedPreferencesUtils;
import com.payment.ktb.utils.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Date;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by syd on 2016/6/14.
 */
public class SettleSubmitActivity extends BaseActivity {




    String rateCharge = "";
    String rateFee = "";
    String maintainace = "";
    String receive = "";
    String prelinkId;
    String reallinkId;

    @BindView(R.id.tv_settlesubmit_amount)
    TextView tv_settlesubmit_amount;
    @BindView(R.id.et_settlesubmit_amount)
    EditText et_settlesubmit_amount;
    @BindView(R.id.tv_settlesubmit_typedesc)
    TextView tv_settlesubmit_typedesc;
    @BindView(R.id.tv_settlesubmit_amountMin)
    TextView tv_settlesubmit_amountMin;
    @BindView(R.id.tv_settlesubmit_amountMax)
    TextView tv_settlesubmit_amountMax;
    @BindView(R.id.tv_settlesubmit_time)
    TextView tv_settlesubmit_time;
    @BindView(R.id.tv_settlesubmit_notes)
    TextView tv_settlesubmit_notes;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_settlesubmit);
        ButterKnife.bind(this);
        initTitle("结算管理");
        tv_settlesubmit_amountMin.setText(SharedPreferencesUtils.getString(ConstantsPay.nocardMcgMin) + "元");
        tv_settlesubmit_amountMax.setText(SharedPreferencesUtils.getString(ConstantsPay.nocardMcgMax) + "元");
        tv_settlesubmit_time.setText(SharedPreferencesUtils.getString(ConstantsPay.nocardMcgStart) + "-" + SharedPreferencesUtils.getString(ConstantsPay.nocardMcgEnd));
        if (ConstantsSettle.orderType.equals(ConstantsSettle.orderTypeT0)) {
            if (ConstantsSettle.payType.equals(ConstantsSettle.payTypeNocard)) {
                tv_settlesubmit_typedesc.setText("无卡快捷收款");
                tv_settlesubmit_amount.setText(ConstantsSettle.t0EnBalanceNocard);
                tv_settlesubmit_notes.setText(SharedPreferencesUtils.getString(ConstantsPay.T0Mcg));
            } else if (ConstantsSettle.payType.equals(ConstantsSettle.payTypeQr)) {
                tv_settlesubmit_typedesc.setText("微信快捷收款");
                tv_settlesubmit_amount.setText(ConstantsSettle.t0EnBalanceQr);
                tv_settlesubmit_notes.setText(SharedPreferencesUtils.getString(ConstantsPay.T0Mcg));
            }

        } else if (ConstantsSettle.orderType.equals(ConstantsSettle.orderTypeT1)){

            if (ConstantsSettle.payType.equals(ConstantsSettle.payTypeNocard)) {
                tv_settlesubmit_typedesc.setText("无卡普通收款");
                tv_settlesubmit_amount.setText(ConstantsSettle.t1EnBalanceNocard);
                tv_settlesubmit_notes.setText(SharedPreferencesUtils.getString(ConstantsPay.T1Mcg));
            } else if (ConstantsSettle.payType.equals(ConstantsSettle.payTypeQr)) {
                tv_settlesubmit_typedesc.setText("微信普通收款");
                tv_settlesubmit_amount.setText(ConstantsSettle.t1EnBalanceQr);
                tv_settlesubmit_notes.setText(SharedPreferencesUtils.getString(ConstantsPay.T1Mcg));
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        prelinkId = String.valueOf(new Date().getTime());
        reallinkId = String.valueOf(new Date().getTime());
    }

    @OnClick(R.id.btn_settlesubmit_submit)
    public void clickEvent(View view) {


        if (TextUtils.isEmpty(et_settlesubmit_amount.getText().toString().trim()) ) {
            ToastUtils.showToast("请输入结算金额！");
        }
        else if (Double.parseDouble(et_settlesubmit_amount.getText().toString().trim()) > Double.parseDouble(tv_settlesubmit_amount.getText().toString().trim())) {
           ToastUtils.showToast("最大结算金额为" + tv_settlesubmit_amount.getText().toString().trim());
            } else {
            //预结算
            PreSettle();
        }

    }


    /**
     *
     */
    private void PreSettle() {

        progressDialogUtils.showProgress();

        //构造传输参数

        String type = ConstantsSettle.orderType;
        String payType = ConstantsSettle.payType;
        String amount = et_settlesubmit_amount.getText().toString().trim();
        String issued = ConstantsSettle.issuedTypePre;
        String token = SharedPreferencesUtils.getString(ConstantsUser.userToken);
        //MD5（orderType+amount+issued+key）
        String sign = Md5Utils.md5Hex(amount + issued + prelinkId + payType + type + SharedPreferencesUtils.getString(ConstantsUser.userKey));



        //将参数放入map中
        HashMap<String, String> map = new HashMap<String,String>();

        map.put("linkId",prelinkId);
        map.put("type",type);
        map.put("payType",payType);
        map.put("amount",amount);
        map.put("issued",issued);
        map.put("token",token);
        map.put("sign",sign);

        //向服务器发送请求
        HttpUtils.HttpRequestByVollery(HttpUrls.URL, HttpActions.nocardSettleMcgState, map, mQueue, new HttpCallbackListener() {
            @Override
            public void onFinish(String response) {

                progressDialogUtils.dismissProgress();

                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String code = jsonObject.optString("code");
                    if (Constants.NORMAL_CODE.equals(code)) {

                        ConstantsSettle.settleNo = jsonObject.optString("settleNo");
                        rateCharge = jsonObject.optString("rateCharge");
                        rateFee = jsonObject.optString("rateFee");
                        maintainace = jsonObject.optString("maintainace");
                        receive = jsonObject.optString("receive");
                        confirmWithDialog();
                    } else if (jsonObject.optString("code").equals(Constants.ERR605_CODE)) {

                        AlertDialogUtils.showAlertDialog(mContext, jsonObject.optString("msg"), "取消", "绑定结算卡", new AlertInterface() {
                            @Override
                            public void confirm(Dialog alertDialog) {
                                startActivity(SettleBankCardManageNoCard.class);
                            }
                        });

                    } else {
                        AlertDialogUtils.showAlertDialog(mContext, jsonObject.optString("msg"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    AlertDialogUtils.showAlertDialog(mContext, getResources().getString(R.string.json_parse_error));
                }
            }

            @Override
            public void onError(VolleyError volleyError) {

                progressDialogUtils.dismissProgress();
                AlertDialogUtils.showAlertDialog(mContext, getResources().getString(R.string.fail_to_connect_server));
            }
        });

    }



    /**
     * 预结算弹出框
     */
    private void confirmWithDialog() {

        final AlertDialog dialog = new AlertDialog.Builder(mContext).create();
        dialog.show();
        dialog.setCanceledOnTouchOutside(false);
        dialog.setCancelable(false);
        dialog.getWindow().setContentView(R.layout.alertdialog_withdrawl);
        ((TextView)dialog.getWindow().findViewById(R.id.tv_withdrawl_amount)).setText(et_settlesubmit_amount.getText().toString().trim());
        ((TextView)dialog.getWindow().findViewById(R.id.tv_withdrawl_rateCharge)).setText(rateCharge);
        ((TextView)dialog.getWindow().findViewById(R.id.tv_withdrawl_rateFee)).setText(rateFee);

        if ("0".equals(maintainace)) {
            ((LinearLayout)dialog.getWindow().findViewById(R.id.ll_withdrawl_refund)).setVisibility(View.GONE);
        }else {
            ((LinearLayout)dialog.getWindow().findViewById(R.id.ll_withdrawl_refund)).setVisibility(View.VISIBLE);
            ((TextView)dialog.getWindow().findViewById(R.id.tv_withdrawl_maintainace)).setText(maintainace);
        }


        ((TextView)dialog.getWindow().findViewById(R.id.tv_withdrawl_arrival_receive)).setText(receive);
        dialog.getWindow().findViewById(R.id.ad_withdrawl_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        dialog.getWindow().findViewById(R.id.ad_withdrawl_confirm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
               Settle();
            }
        });

    }







    /**
     *
     */
    private void Settle() {

        progressDialogUtils.showProgress();

        //构造传输参数

         String type = ConstantsSettle.orderType;
         String payType = ConstantsSettle.payType;
        String amount = et_settlesubmit_amount.getText().toString().trim();
         String issued = ConstantsSettle.issuedTypeReal;
        String token = SharedPreferencesUtils.getString(ConstantsUser.userToken);
        //MD5（orderType+amount+issued+key）
        String sign = Md5Utils.md5Hex(amount + issued +reallinkId + payType + type + SharedPreferencesUtils.getString(ConstantsUser.userKey));



        //将参数放入map中
        HashMap<String, String> map = new HashMap<String,String>();

        map.put("linkId",reallinkId);
        map.put("type",type);
        map.put("payType",payType);
        map.put("amount",amount);
        map.put("issued",issued);
        map.put("token",token);
        map.put("sign",sign);

        //向服务器发送请求
        HttpUtils.HttpRequestByVollery(HttpUrls.URL, HttpActions.nocardSettleMcgState, map, mQueue, new HttpCallbackListener() {
            @Override
            public void onFinish(String response) {

                progressDialogUtils.dismissProgress();

                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String code = jsonObject.optString("code");
                    if (Constants.NORMAL_CODE.equals(code)) {
                        ConstantsSettle.amount = et_settlesubmit_amount.getText().toString().trim();
                        ConstantsSettle.settleNo = jsonObject.optString("settleNo");
                        startActivity(NocardSettleResultWaitActivity.class);

                    } else {
                        AlertDialogUtils.showAlertDialog(mContext, jsonObject.optString("msg"));

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    AlertDialogUtils.showAlertDialog(mContext, getResources().getString(R.string.json_parse_error));
                }
            }

            @Override
            public void onError(VolleyError volleyError) {

                progressDialogUtils.dismissProgress();
                AlertDialogUtils.showAlertDialog(mContext, getResources().getString(R.string.fail_to_connect_server));
            }
        });

    }







}
